package com.ahdms.es.engine;

import com.ahdms.es.bean.SealInfo;
import com.ahdms.es.exceptions.InvalidSealDateException;
import com.ahdms.es.exceptions.InvalidSealFormatException;
import com.ahdms.es.exceptions.InvalidSignedValueException;
import com.ahdms.es.exceptions.VerifySealException;
import com.ahdms.es.gm.v4.SESeal;
import com.ahdms.es.util.DataConvert;
import org.bouncycastle.asn1.x509.Certificate;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 * @author qinxiang
 * @date 2021-04-13 15:28
 */
public class SeSealGBVerifyEngine extends SeSealVerifyEngine {

    /**
     * 电子印章数据格式(国标规范)
     */
    private final SESeal seSeal;

    /**
     * 制章人证书
     */
    private final Certificate cert;

    private SealInfo sealInfo;

    public static SeSealGBVerifyEngine getInstance(SESeal seSeal) throws InvalidSealFormatException {
        try {
            if (seSeal != null) {
                return new SeSealGBVerifyEngine(seSeal);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new InvalidSealFormatException();
    }

    public static SeSealGBVerifyEngine getInstance(byte[] seSealData) throws InvalidSealFormatException {
        try {
            if (seSealData != null) {
                return new SeSealGBVerifyEngine(seSealData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new InvalidSealFormatException();
    }

    public SeSealGBVerifyEngine(SESeal seSeal) {
        this.seSeal = seSeal;
        this.cert = Certificate.getInstance(this.seSeal.getCert().getOctets());
//        this.sealInfo = DataConvert.toSealInfo(seSeal);
    }

    public SeSealGBVerifyEngine(byte[] seSealData) {
        this.seSeal = SESeal.getInstance(seSealData);
        this.cert = Certificate.getInstance(this.seSeal.getCert().getOctets());
//        this.sealInfo = DataConvert.toSealInfo(seSeal);
    }

    /**
     * 验证电子印章签名值是否正确
     *
     * @throws IOException
     */
    @Override
    public void verifySignData() throws IOException, VerifySealException {
        super.verifySignData(cert, seSeal.getSignAlgID().getId(), seSeal.geteSealInfo().getEncoded(), seSeal.getSignedValue().getBytes());
    }

    /**
     * 验证电子印章的有效期
     *
     * @throws ParseException
     */
    @Override
    public void verifyDate() throws ParseException, VerifySealException {
        Date startDate = seSeal.geteSealInfo().getProperty().getValidStart().getDate();
        Date endDate = seSeal.geteSealInfo().getProperty().getValidEnd().getDate();
        Date nowDate = new Date();
        verifyDate(nowDate, startDate, endDate);
    }

    @Override
    public Certificate getCert() {
        return this.cert;
    }

    @Override
    public SealInfo getSealInfo() {
        return DataConvert.toSealInfo(seSeal);
    }
}
